class Solution {
public:
    vector<int> father;
    int find(int x){
        if(x != father[x]){
            father[x] = find(father[x]);
        }
        return father[x];
    }
    void Union(int u,int v){
        int x = find(u);
        int y = find(v);
        if(x == y) return;
        if(x > y) swap(x,y);
        father[x] = y;
    }
    
    int closedIsland(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        
        father.resize(m*n+1);
        for(int i = 0;i <= m*n;i++){
            father[i] = i;
        }
        
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                int index = i * n + j;
                if(grid[i][j] == 1){
                    father[index] = -1;
                    continue;
                }
                
                if(i == 0 || i == m-1 || j == 0 || j == n-1){
                    father[index] = m*n;
                }
                if(i > 0 && grid[i-1][j] == 0){
                    Union(index,index-n);
                }
                if(j > 0 && grid[i][j-1] == 0){
                    Union(index,index-1);
                }
            }
        }
        int ret = 0;
        for(int i = 0;i < m*n;i++){
            if(father[i] == i){
                ret++;
            }
        }
        return ret;
    }
};

